<template>
  <div class="main" ref="main" style="width: 100%; height: 400px"></div>
</template>
<script setup>
import { ref, watchEffect, computed } from 'vue'
//  按需引入 echarts
import * as echarts from 'echarts'
const main = ref('main')

const props = defineProps({
  echartType: {
    type: String,
    default: 'bar'
  },
  chartData: {
    type: Array
  }
})
watchEffect(() => {
  // 监听echartType变化
  if (props.chartData.length > 0) {
    init()
  }
})
const computedChartData = computed(() => {
  const transformedArray = []
  // 添加表头
  transformedArray.push(['number', '新闻数', '轮播图数'])
  // 遍历原始数组并转换格式
  props.chartData.forEach((item) => {
    // transformedArray.push([item.date, item.newsCount, item.bannerCount])
    // 数据太少，伪造一些数据演示
    transformedArray.push([item.date, item.newsCount * 100, item.bannerCount * 200])
  })
  return transformedArray
})

const computedOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      orient: 'vertical',
      right: 'center',
      top: 0
    },
    dataset: {
      source: computedChartData.value
    },
    xAxis: { type: 'category' },
    yAxis: {},
    series: [{ type: props.echartType }, { type: props.echartType }]
  }
})
function init() {
  // 基于准备好的dom，初始化echarts实例
  let myChart = echarts.getInstanceByDom(main.value)
  if (myChart == null) {
    myChart = echarts.init(main.value)
  }
  // 指定图表的配置项和数据
  let option = computedOption.value
  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option)
}
</script>

<style scoped lang="scss"></style>
